package me.numark.fragments;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import me.numark.R;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.Constants;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link GetVerifyCodeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class GetVerifyCodeFragment extends Fragment implements View.OnClickListener {

    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_MOBILE = "mobile";

    private String mobile;

    private RegisterListener mListener;

    private EditText verifyCodeEdit;

    private TextView getVerifyButton;

    private TextView rightButton;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param mobile Mobile number.
     * @return A new instance of fragment GetVerifyCodeFragment.
     */
    public static GetVerifyCodeFragment newInstance(String mobile) {
        GetVerifyCodeFragment fragment = new GetVerifyCodeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_MOBILE, mobile);
        fragment.setArguments(args);
        return fragment;
    }

    public GetVerifyCodeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mobile = getArguments().getString(ARG_MOBILE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_get_verify_code, container, false);
        verifyCodeEdit = (EditText) view.findViewById(R.id.verify_code_edit);
        verifyCodeEdit.requestFocus();
        getVerifyButton = (TextView) view.findViewById(R.id.get_verify_code_button);
        getVerifyButton.setOnClickListener(this);
        getVerifyButton.setEnabled(true);
        verifyCodeEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s != null && s.length() == getResources()
                        .getInteger(R.integer.verify_code_length)) {
                    rightButton.setEnabled(true);
                } else {
                    rightButton.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText(R.string.get_verify_code);
        view.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        rightButton = (TextView) view.findViewById(R.id.right_text);
        rightButton.setEnabled(false);
        rightButton.setOnClickListener(this);
        rightButton.setText(R.string.next_step);
        getVerifyCode();
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (RegisterListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        finishCountdown();
        mListener = null;
    }

    private static final int MSG_COUNT_DOWN = 30;

    private static final int MSG_COUNT_DOWN_BEGIN = 31;

    private static final int MSG_COUNT_DOWN_FINISHED = 32;

    private int countDown = Constants.SMS_COUNT_DOWN_TIME;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_verify_code_button:
                if (getVerifyButton.isEnabled()) {
                    getVerifyCode();
                }
                break;
            case R.id.right_text:
                doVerify();
                break;
        }
    }

    private void doVerify() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
                NetworkConstants.REGISTER_SMS_URL + "?cellphone=" + mobile + "&code="
                        + verifyCodeEdit.getText(), null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                LogUtils.d("doVerify, response is " + response);
                if (response.optBoolean("ret")) {
                    JSONObject data = response.optJSONObject("data");
                    if (data != null) {
                        Settings.saveLogInInfo(data.optString("uid"),
                                data.optString("token"));
                    }
                    mListener.onNext(GetVerifyCodeFragment.this, null);
                } else {
                    mListener.onFailure(
                            response.optString("msg", getString(R.string.verify_failed)));
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mListener.onFailure(getString(R.string.verify_failed));
            }
        });
        NetworkHelper.getInstance().getRequestQueue().add(request);
        NetworkHelper.getInstance().getRequestQueue().start();
        mListener.onShowProgress(getString(R.string.verifying));
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (isDetached()) {
                return;
            }
            switch (msg.what) {
                case MSG_COUNT_DOWN_BEGIN:
                    getVerifyButton.setEnabled(false);
                    sendEmptyMessage(MSG_COUNT_DOWN);
                    break;
                case MSG_COUNT_DOWN:
                    countDown--;
                    getVerifyButton.setText(
                            String.format(getString(R.string.count_down_time_left), countDown));
                    if (countDown > 0) {
                        sendEmptyMessageDelayed(MSG_COUNT_DOWN, 1000);
                    } else {
                        sendEmptyMessage(MSG_COUNT_DOWN_FINISHED);
                    }
                    break;
                case MSG_COUNT_DOWN_FINISHED:
                    getVerifyButton.setText(R.string.get_verify_code);
                    getVerifyButton
                            .setTextColor(getResources().getColor(android.R.color.white));
                    getVerifyButton.setEnabled(true);
                    countDown = Constants.SMS_COUNT_DOWN_TIME;
                    break;

            }

        }
    };

    private void finishCountdown() {
        countDown = 0;
        mHandler.removeMessages(MSG_COUNT_DOWN);
    }

    private void getVerifyCode() {
        mHandler.sendEmptyMessage(MSG_COUNT_DOWN_BEGIN);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                NetworkConstants.REGISTER_SMS_URL + "?cellphone=" + mobile, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        LogUtils.d("onResponse, response is " + response);
                        if (response.optBoolean("ret")) {
                            mListener.onSuccess(getString(R.string.get_registration_sms_success));
                            Settings.saveMobile(mobile);
                        } else {
                            mListener.onFailure(
                                    response.optString("msg",
                                            getString(R.string.get_registration_sms_failed)));
                            if (response.optInt("code") == 2001 && isAdded()) {
                                getActivity().getFragmentManager().popBackStack();
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mListener.onFailure(getString(R.string.get_registration_sms_failed));
            }
        });
        NetworkHelper.getInstance().getRequestQueue().add(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }


}
